package cn.lwj.controller;

import cn.lwj.common.R;
import cn.lwj.pojo.Employee;
import cn.lwj.service.EmployeeService;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import oracle.jrockit.jfr.events.RequestableEventEnvironment;
import org.apache.ibatis.javassist.compiler.ast.Variable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;


//    员工登录
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee emp){

//        将用户输入的密码进行MD5加密
        String password = emp.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

//        创建一个mp条件查询对象
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        /*
        * 根据用户名进行查询
        * 第一个参数表示根据用户名进行查询员工信息
        * 第二个参数表示具体的员工用户名
        * */
        queryWrapper.eq(Employee::getUsername,emp.getUsername());
//        调用service层业务逻辑 将条件对象传递过去 根据用户名查询员工信息
        Employee employee = employeeService.getOne(queryWrapper);

//        判断员工是否存在
        if(employee == null){
            return R.error("员工不存在，登录失败");
        }

//        判断密码是否正确
        if( password == null ||  password == "" || !password.equals(employee.getPassword())){
            return R.error("密码错误，登录失败");
        }

//        判断员工账号状态是否正常
        if(employee.getStatus() == 0){
            return R.error("账号已冻结");
        }

//        否则就登录成功 将员工id保存至session当前
        request.getSession().setAttribute("employee",employee.getId());
        return R.success(employee);
    }


//    退出登录
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
//        如果session域用户信息存在 则移除 否则退出失败
        if(request.getSession().getAttribute("employee") == null)
            return R.error("退出失败");
//        响应退出信息
//        尽量不是他        request.getSession().invalidate(); 这样会清空session域
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

//    新增员工

    /**
     *
     * @param employee
     * @param request
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee,HttpServletRequest request){  // @RequestBody表示参数来自于请求体
        log.info("开始新增用户");
//        模拟异常
//        System.out.println(1/0);
//        如果输出为空 添加失败
        if(employee == null)
            return  R.error("添加失败");
//        不为空 判断用户名是否存在
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername,employee.getUsername());
        Employee e = employeeService.getOne(qw);
        if(e != null){
            return  R.error("用户名已存在");
        }
//        用户名不存在可以添加员工
//        添加创建者信息

//        手动设置创建者和更新者  新增时间
        employee.setCreateUser((Long) request.getSession().getAttribute("employee"));
        employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
//        DigestUtils.md5DigestAsHex("123456".getBytes());
//        设置初识密码
        //        将用户输入的密码进行MD5加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        boolean save = employeeService.save(employee);
        if(save){
            return R.success("添加成功");
        }else{
            return  R.error("添加失败");
        }
    }

//    分页查询

    /**
     *
     * @param page  查询第几页
     * @param pageSize  一共查询几条
     * @param name  模糊查询参数
     * @return
     */
    @GetMapping("/page")
    public R<Page> selectEmployeeByPage(Integer page, Integer pageSize,String name){

//        log.info("page = " + page + " pageSize = "  + pageSize + " name = " + name);

//        1.构造分页查询对象
        Page pageInfo = new Page<>(page ,pageSize);
//        2.构建条件查询对象 name 存在则进行模糊查询
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper();
//        lqw.like(name != null,Employee::getUsername,name);
        lqw.like(!StringUtils.isEmpty(name),Employee::getUsername,name);
        lqw.orderByDesc(Employee::getUpdateTime);
//        3.执行查询操作
        Page p = employeeService.page(pageInfo, lqw);
        return R.success(p);
    }


//    修改状态
    @PutMapping
    public R<String> updateStatus(@RequestBody Employee employee,HttpServletRequest request){
        System.out.println(employee);
//        1.创建条件查询对象
//        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(Employee::getId,employee.getId());
//        2.执行条件查询操作
        long loginEmployeeId = (long) request.getSession().getAttribute("employee");
//        Employee e = employeeService.getById(loginEmployeeId);
        employee.setUpdateUser(loginEmployeeId);
        employee.setUpdateTime(LocalDateTime.now());
//        employee.setId(1622872658212966402L);
        boolean res = employeeService.updateById(employee);
        if(res){
            return R.success("修改成功");
        }else{
            return R.error("修改失败");
        }
    }

//    根据id获取员工信息
    @GetMapping("/{id}")
    public R<Employee> queryEmployeeById(@PathVariable long id){
        Employee e = employeeService.getById(id);
        if(e != null){
            return  R.success(e);
        }else {
            return R.error("查询失败");
        }
    }

//    更新员工信息 (修改员工信息)
//    @PutMapping("/update")
//    public R<String> update(Employee employee){
//        log.info(employee.toString());
//        return  null;
//    }


}
